# encoding: utf-8

import os
from glob import glob
from urllib.parse import quote as url_quote
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.responses import StreamingResponse
from fastapi.responses import FileResponse
from fastapi.templating import Jinja2Templates

from fastapi.responses import RedirectResponse

import uvicorn

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get("/")
def index(request: Request):
    return RedirectResponse("/home", status_code=302)


@app.get("/home")
def home(request: Request):
    # mp4_list = []
    mp4_path = r"E:/data/mp4/*[mp4,MP4]"
    mp4_list = glob(mp4_path)
    mp4_dict = {}
    for x in mp4_list:
        mp4_dict[x] = url_quote(x)
    total = len(mp4_list)
    # print(mp4_list[:10])
    return templates.TemplateResponse("index.html", {"request": request, "mp4_dict": mp4_dict, "total": total})


@app.get("/playVideo/{file_path:path}")
def play_vidoe(file_path: str):
    def iter_file(_path: str):
        with open(_path, "rb") as f:
            yield from f

    return StreamingResponse(iter_file(file_path), media_type="video/mp4")


@app.get("/download/")
def download_vidoe(file_path: str):
    def iter_file(_path: str):
        with open(_path, "rb") as f:
            yield from f
            # return f

    return FileResponse(file_path)


@app.get("/play/")
def play(request: Request, file_path: str):

    print("file_name:", file_path)

    # video_base_name = os.path.basename(file_path)
    # print(video_base_name)
    # pv_url = app.url_path_for(f"/playVideo/")
    # print("pv_url", pv_url)

    return templates.TemplateResponse("play.html", {"request": request, "file_name": file_path})


if __name__ == '__main__':
    uvicorn.run(app, host="192.168.1.100", port=1235, access_log=True)
